<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="月份">
                <el-date-picker
                  v-model="date"
                  type="month"
                  size="small"
                  class="date-item"
                  style="width: 100%;"
                  format="yyyy - M"
                  value-format="yyyy-M"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务员">
                <table-select
                  :tableColumns="[{prop:'name',label:'业务员名称',width: '280'}]"
                  :value.sync="query.userIds"
                  placeholder="请选择业务员"
                  url="/api/dropDown/sysUserList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户分类" prop="customerTypeId">
                <TreeSelect
                  v-model="query.customerTypeIds"
                  :options="typeList"
                  placeholder="客户分类"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @select="onCustomerNode"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户区域">
                <TreeSelect
                  v-model="query.customerAreaIds"
                  :options="areaList"
                  style="width: 100%"
                  placeholder="区域"
                  :normalizer="normalizer"
                  multiple
                  @input="getArea"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-button class="filter-item"  size="mini" type="primary" @click="queryReport">搜索</el-button>
              <el-button class="filter-item" plain   size="mini" type="primary"
                         @click="crud.resetQuery()" >重置</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="小计列">
                <el-checkbox-group @change="getChange" v-model="groupColumn">
                  <el-checkbox label="userId" value="userId" key="userId">业务员</el-checkbox>
                  <el-checkbox label="customerTypeId" value="customerTypeId" key="customerTypeId">客户分类</el-checkbox>
                  <el-checkbox label="customerAreaId" value="customerAreaId" key="customerAreaId">销售区域</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <crudOperation >
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="doExport"
        >导出</el-button>
      </crudOperation>
      <!--表格渲染-->
      <el-table ref="table"
                height="500"
                show-summary
                stripe border v-loading="crud.loading" :data="backData" size="small" style="width: 100%;"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @cell-dblclick="toDetailPlus"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column :render-header="crud.renderHeader"  fixed type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" width="100px" fixed v-if="groupColumnSelectList.includes('userId')" prop="userName" label="业务员"/>
        <el-table-column :render-header="crud.renderHeader" width="100px" fixed v-if="groupColumnSelectList.includes('customerTypeId')" prop="customerTypeName" label="客户分类"/>
        <el-table-column :render-header="crud.renderHeader" width="100px" fixed v-if="groupColumnSelectList.includes('customerAreaId')" prop="customerAreaName" label="区域"/>
        <el-table-column :render-header="crud.renderHeader" align="center" width="100px" v-for="item in columnNames" :key="item" :prop="item" :label="item.match(/\d+/g).join('')"/>
        <el-table-column :render-header="crud.renderHeader"  width="100px" fixed="right" prop="distinctVisitCount" label="有效拜访次数" />
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
  import reportSalesmanVisit from '@/api/erp/reportSalesmanVisit'
  import {queryAll} from '@/api/erp/reportSalesmanVisit'
  import CRUD, {presenter, header, form, crud} from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import TreeSelect from '@riophae/vue-treeselect'
  import {getAreaTree} from "@/api/erp/basCustomerArea";
  import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
  import {download} from "@/api/data";
  import {downloadFile} from "@/utils";


  // crud交由presenter持有
  let thisDate = new Date().getFullYear() +'-'+ (new Date().getMonth() + 1)
  const defaultCrud = CRUD({
    title: '业务员巡店汇总报表', url: '/api/reportSalesmanVisit/queryAll', sort: 'id,desc',
    query: {
      month: thisDate.split('-')[1],
      year: thisDate.split('-')[0],
      groupColumn:'userId,customerTypeId,customerAreaId'
    },
    optShow: {
      add: false,
      edit: false,
      del: false,
      download: false,
      leadingIn: false,
      enable: false,
      disable: false,
    },
    crudMethod: {...reportSalesmanVisit}
  })
  const defaultForm = {
    thisDate:thisDate,
    userIds: null,
    customerTypeId: null,
    areas: null
  }
  export default {
    name: 'reportSalesmanVisit',
    components: {pagination, crudOperation, rrOperation, udOperation, TreeSelect},
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    data() {
      return {
        groupColumn:['userId','customerTypeId','customerAreaId'],
        groupColumnSelectList:['userId','customerTypeId','customerAreaId'],
        typeList: [],
        areaList: [],
        id:'',
        columnNames: [],
        year:null,
        month:null,
        customerAreaIds:null,
        customerTypeIds:[],
        userIds:null,
        date:thisDate,
        // backData: []
      }
    },
    computed: {
      backData: function (data) {
        this.columnNames = [];
        let index = 0
        if (data.crud.data && data.crud.data.length > 0) {
          console.log(data.crud)
          data.crud.data.map(item => {
            Object.keys(item).map(obj => {
              // obj.indexOf('-') > -1 && this.columnNames.indexOf(obj) === -1
              if (obj.includes('visitDuration') && this.columnNames.indexOf(obj) === -1 && index < this.crud.daysOfMonth) {
                index++
                this.columnNames.push(obj);
              }
            });
          });
        }
        return data.crud.data
      }
    },
    watch: {
      'groupColumnSelectList':{
        handler(n){
          let groupColumn =this.groupColumnSelectList.join(',')
          this.$set(this.query,'groupColumn',groupColumn)
        },
        deep: true
      }
    },
    created() {
      this.getTypeList()
      this.getAreaList()
    },
    methods: {
      toDetailPlus(row,column,data,cell){
        let dataList={}
        if (column.label==='有效拜访次数'){
          dataList={
            customerAreaIds:row.customerAreaId,
            customerTypeIds:row.customerTypeId,
            month:this.query.month,
            year:this.query.year,
            userIds:row.userId,
          }
        }else if (Number(column.label)){
          dataList={
            customerAreaIds:row.customerAreaId,
            customerTypeIds:row.customerTypeId,
            month:this.query.month,
            year:this.query.year,
            userIds:row.userId,
            day:column.label
          }
        }else {
          return
        }
        sessionStorage.setItem('year',JSON.stringify(dataList))
        // sessionStorage.setItem('month',JSON.stringify(this.query.month))
        // console.log(`customerVisitRecordTableView/${ids}?year=${this.query.year}&month=${this.query.month}`)
        // this.$router.push({
        //   path: '/customerVisitRecordTableView',
        //   query:data
        // })
        this.crud.toDetailPlus('customerVisitRecordTableView',row.userId)
        // this.$router.push({ path: `customerVisitRecordTableView/${data.userId}` })
        // const data = {
        //   year: thisYear,
        //   month:thisMonth,
        //   customerAreaIds:this.customerAreaIds,
        //   customerTypeIds:this.customerTypeIds.join(','),
        //   userIds:this.userIds,
        //   groupColumn:'userId,customerTypeId,customerAreaId'
        // }
        // queryDetail(data).then(res=>{
        //   console.log(res)
        // })
      },
      getChange(val){
        this.groupColumnSelectList = val
      },
      doExport(){
        this.crud.downloadLoading = true
        download('/api/reportSalesmanVisit/export', this.crud.getQueryParams(),this.crud.queryType).then(result => {
          downloadFile(result, this.crud.title + '数据', 'xlsx')
          this.crud.downloadLoading = false
        }).catch(() => {
          this.crud.downloadLoading = false
        })
      },
      queryReport(){
        this.query.year=this.date.split('-')[0]
        this.query.month=this.date.split('-')[1]
        this.crud.toQuery()
        // const data = {
        //   year: this.date.split('-')[0],
        //   month:this.date.split('-')[1],
        //   customerAreaIds:this.customerAreaIds,
        //   customerTypeIds:this.customerTypeIds.join(','),
        //   userIds:this.userIds,
        //   groupColumn:'userId,customerTypeId,customerAreaId'
        // }
        // console.log(data)
        // queryAll(data).then(res=>{
        //   // this.backData = res.data.content
        //   // console.log(res.data.content)
        // })
      },
      getAreaList() {//区域
        getAreaTree().then(res => {
          this.areaList = res
        })
      },
      getTypeList() {
        getCustomerTypeTree({page: 0, size: 999}).then(res => {
          this.typeList = res
        })
      },
      normalizer(node) {
        //去掉children=[]的children属性
        if (node.children == null || (node.children && node.children.length == 0)) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      onCustomerNode(node){
        this.query.customerTypeIds = this.getNode(node,this.query.customerTypeIds?this.query.customerTypeIds:'')
      },
      getArea(val){
        let str = ''
        console.log(this.areaList)
        val.forEach(item=>{
          const itemNode = this.getTreeName(this.areaList,item)
          str = this.getNode(itemNode,str)
        })
        this.query.customerAreaIds = str
      },
      getTreeName(treeList,id){
        let _this=this
        for (let i = 0; i < treeList.length; i++) {
          let treeItem=treeList[i]
          if(treeItem.id===id){
            return treeItem
          }else{
            if(treeItem.children && treeItem.children.length>0){
              let res=_this.getTreeName(treeItem.children,id)
              if(res){
                return res
              }
            }
          }
        }
      },
      getNode(node,str){
        if (node.children){
          for (let i =0;i<node.children.length;i++){
            str = this.getNode(node.children[i],str)
          }
        }
        return str+=node.id+ ','
      },
      // 获取数据前设置好接口地址
      [CRUD.HOOK.beforeRefresh]() {
        return true
      }, // 新增与编辑前做的操作
      [CRUD.HOOK.afterToCU](crud, form) {
      },

    }
  }
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
